package cn.learn.activiti.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author huangyezhan
 * @version 1.0
 * @date 2021年03月04日9:38
 */
@Slf4j
@Configuration
public class DemoApplicationConfiguration {

    @Bean
    public UserDetailsService myUserDetailsService() {
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
        /*
         * 这里添加用户，后面处理流程时用到的任务负责人，需要添加在这里
         * ROLE_、GROUP_ 这两个是前缀，测试的时候不要把前缀也copy进去了
         */
        String[][] usersGroupsAndRoles = {
                {"14488888888", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam"},

                {"jack", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam"},
                {"rose", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam"},
                {"tom", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam"},
                {"jerry", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam"},
                {"other", "password", "ROLE_ACTIVITI_USER", "GROUP_otherTeam"},
                {"system", "password", "ROLE_ACTIVITI_USER"},
                {"admin", "password", "ROLE_ACTIVITI_ADMIN"},
        };

        for (String[] user : usersGroupsAndRoles) {
            List<String> authoritiesStrings = Arrays.asList(Arrays.copyOfRange(user, 2, user.length));
            log.info("> Registering new user: " + user[0] + " with the following Authorities[" + authoritiesStrings + "]");

            User user1 = new User(user[0], passwordEncoder().encode(user[1]),
                    authoritiesStrings.stream()
                            .map(s -> new SimpleGrantedAuthority(s))
                            .collect(Collectors.toList()));

            inMemoryUserDetailsManager.createUser(user1);
        }
        return inMemoryUserDetailsManager;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    public static void main(String[] args) {
        DemoApplicationConfiguration configuration = new DemoApplicationConfiguration();
        configuration.myUserDetailsService();
    }

}